package com.zcxy.fast.util;

import cn.hutool.core.collection.CollectionUtil;
import com.zcxy.fast.entity.SysDictItem;
import com.zcxy.fast.service.ISysDictItemService;
import com.zcxy.fast.utils.RedisUtils;
import com.zcxy.fast.utils.SpringContextHolder;
import com.zcxy.fast.vo.SysDictItemVo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class SysdictUtil {
    public static final String PRESYSDICT = "fastdict_";

    private static final long ONEDAY = 24 * 60 * 60 * 1000;

    public static Object getSysdictValue(String dictCode, String itemCode) {
        RedisUtils redisUtils = SpringContextHolder.getBean(RedisUtils.class);
        Map map = redisUtils.hmget(SysdictUtil.PRESYSDICT + dictCode);

        if (CollectionUtil.isNotEmpty(map)) {
            return map.get(itemCode);
        } else {
            return SysdictUtil.getSysdictValueByDb(dictCode, itemCode);
        }
    }

    private static Map putSysdictValue(String dictCode, List<SysDictItemVo> sysDictItems) {
        Map map = new HashMap();
        if (CollectionUtil.isNotEmpty(sysDictItems)) {
            map = sysDictItems.stream().collect(Collectors.toMap(SysDictItemVo::getCode, SysDictItemVo::getName));
            RedisUtils redisUtils = SpringContextHolder.getBean(RedisUtils.class);
            redisUtils.hmset(SysdictUtil.PRESYSDICT + dictCode, map);
        }
        return map;
    }


    private static Object getSysdictValueByDb(String dictCode, String itemCode) {
        ISysDictItemService sysDictItemService = SpringContextHolder.getBean(ISysDictItemService.class);
        SysDictItem sysDictItem = new SysDictItem();
        sysDictItem.setDictCode(dictCode);
        List<SysDictItemVo> items = sysDictItemService.queryList(sysDictItem);
        return SysdictUtil.putSysdictValue(dictCode, items).get(itemCode);
    }

    public static String getDictValue(String dictCode, String itemCode) {
        Object value = SysdictUtil.getSysdictValue(dictCode, itemCode);
        if (value != null) {
            return value.toString();
        } else {
            return "";
        }
    }

    /**
     * 根据列表获取相关数据
     */


}
